﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    /// <summary>
    /// 字节数组扩展
    /// </summary>
    public static partial class ByteArrayExtension
    {  
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="data">byte[]要压缩的字节数组</param>
        /// <returns>返回压缩后byte[]</returns>
        public static byte[] Compress(this byte[] data)
        {
            byte[] result;
            using (var baseStream = new MemoryStream())
            {
                var stream = new GZipStream(baseStream, CompressionMode.Compress, true);
                stream.Write(data, 0, data.Length);
                result = baseStream.ToArray();
            }
            return result;
        }
        /// <summary>
        /// 将指定字节数组转换为内存流
        /// </summary>
        /// <param name="this">The @this to act on.</param>
        /// <returns>@this as a MemoryStream.</returns>
        public static MemoryStream ToMemoryStream(this byte[] @this)
        {
            return new MemoryStream(@this);
        }

        /// <summary>
        /// byte[]转换成Image
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static Image ToImage(this byte[] @this)
        {
            using (var ms = new MemoryStream(@this))
            {
                return Image.FromStream(ms);
            }
        }

        /// <summary>
        /// 将指定字节数组中的所有字节解码为一个字符串
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static string ToUTF8String(this byte[] @this)
        {
            return Encoding.UTF8.GetString(@this);
        }

        /// <summary>
        /// 二进制转16进制
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static string ToHexString(this byte[] @this)
        {
            if (@this == null)
            {
                return null;
            }
            var array = new char[checked(@this.Length*2)];
            for (int i = 0; i < @this.Length; i++)
            {
                byte b = @this[i];
                array[2*i] = ((byte) (b >> 4)).GetHexValue();
                array[2*i + 1] = ((byte) (b & 15)).GetHexValue();
            }
            return new string(array);
        }
        
    }
}
